package com.stupidzhe.jdklearning.reflect;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by Mr.W on 2017/11/2.
 */
public class ProxyHandler implements InvocationHandler {

    private Object target;

    public Object bind(Object target) {
        this.target = target;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Object " + proxy.getClass().getName() + "  method: " + method.getName() + "  args:" + args);
        Object res = method.invoke(target, args);
        if (null != res) {
            System.out.println(res);
        }
        System.out.println("执行结束");
        return res;
    }
}

class ProxyTestClass implements FInterface {
    public void print() {
        System.out.println("this is a method of ProxyTestClass class");
    }

    public String print2() {
        System.out.println("this is a method of ProxyTestClass class");
        return "print2 返回参数";
    }

    public static void main(String... args) {
        ProxyHandler proxyHandler = new ProxyHandler();
        FInterface proxyTestClassProxy = (FInterface) proxyHandler.bind(new ProxyTestClass());
        proxyTestClassProxy.print();
        proxyTestClassProxy.print2();
    }
}

interface FInterface {
    void print();

    String print2();
}